import Qs from 'qs';
import { request } from 'umi';

export default (
  url: string,
  method: string,
  params?: any,
  data?: any,
  headers?: Record<string, unknown> | '',
  requestType?: 'json' | 'form',
  options?: Record<string, unknown>,
) => {
  let rest = {} as any;
  const base = {
    method,
    headers: { ...(headers || {}) },
    requestType: requestType || 'json',
    ...(options || {}),
  };
  if (method === ('get' || 'delete' || 'head')) {
    rest = {
      params,
      paramsSerializer: () => {
        return Qs.stringify(params, { arrayFormat: 'brackets' });
      },
    };
  } else if (method === ('post' || 'put' || 'patch')) {
    if (requestType === 'form') {
      const formData = new FormData();
      Object.keys(data).forEach((key) => {
        formData.append(key, data[key]);
      });
      rest = {
        data: formData,
      };
    } else {
      rest = {
        data,
      };
    }
  }
  return request(`/${APP_PROXY}/${url}`, { ...base, ...rest });
};
